﻿using FtpFileBackup.LogHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FtpFileBackup.Client
{
    class Program
    {
        private static string FtpPath => ConfigurationManager.AppSettings["ftpPath"];
        private static string FtpUserID => ConfigurationManager.AppSettings["ftpUserID"];
        private static string FtpPassword => ConfigurationManager.AppSettings["ftpPassword"];
        private static string SavePath => ConfigurationManager.AppSettings["savePath"];
        private static List<string> DBNames => ConfigurationManager.AppSettings["dBNames"].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
        static void Main(string[] args)
        {
            DownloadBackupFile();
        }

        public static void DownloadBackupFile()
        {
            var tasks = new List<Task>();
            string date = DateTime.Now.ToString("yyyyMMdd");

            Action<object> action = dBName =>
            {
                var backupDir = SavePath + (string)dBName + "//";
                if (!Directory.Exists(backupDir)) {
                    Directory.CreateDirectory(backupDir);
                }

                FtpHelper.DownloadFtp(SavePath, $"{(string)dBName}/Backup_{date}.7z", FtpPath, FtpUserID, FtpPassword);
            };

            foreach (var dBName in DBNames)
            {
                tasks.Add(Task.Factory.StartNew(action, dBName));
            }

            try
            {
                Task.WaitAll(tasks.ToArray());

                log4netHelper.Info("备份完成");
            }
            catch (AggregateException e)
            {
                var errMessage = e.InnerExceptions.Aggregate(string.Empty, (cur, next) => { return cur + ";" + next; });

                log4netHelper.Error(errMessage);
            }
        }
    }
}
